#!/bin/bash
#
# $Id$
#

flag_gzip=0
if [ "$1" = "-z" ]; then
    flag_gzip=1
    shift
fi

backup_list=$1
backup_dir=$2

if [ -z "$backup_list" -o -z "$backup_dir" ]; then
echo "usage: `basename $0` <list_file> <backup_name>"
exit 1
fi

cat $backup_list | sed -e '/./{H;$!d;}' -e 'x;/\[commands\]/!d;' | egrep -v "\[commands\]|^$|^#" > $backup_list.commands
cat $backup_list | sed -e '/./{H;$!d;}' -e 'x;/\[files\]/!d;' | egrep -v "\[files\]|^$|^#" > $backup_list.files

source_files=`cat $backup_list.files`
for file in `echo "$source_files"`
do
    du -shL $file
    mfile=`basename $file`
    mdir=`dirname $file`
    mkdir -p $backup_dir/$mdir
    /usr/bin/sudo cp -rp $file $backup_dir/$mdir
done

while read command 
do
    echo $command
    resfile=$(basename $(echo $command | awk '{print $1}'))
    mkdir -p $backup_dir
    $command > $backup_dir/$resfile.out 
done < $backup_list.commands

echo create tar archive ... >&2
/usr/bin/sudo tar -cf $backup_dir.tar $backup_dir
echo delete old files ... >&2
/usr/bin/sudo chown -R $LOGNAME $backup_dir.tar $backup_dir && rm -rf $backup_dir
[ "$flag_gzip" -eq 1 ] && /usr/bin/sudo gzip $backup_dir.tar 

exit 0
